<?php
namespace App\Goods\Handles;

use Illuminate\Support\Str;
use Overtrue\Pinyin\Pinyin;

trait GoodsHandle
{
    /**
     * 生成SPU编号，生成规则：通用名名称中文首字母加年月日时分秒日期（年是两位）加两位随机数
     * @param $name
     * @return string
     */
    public function setSpuHandle($name)
    {
        $pinyin = new Pinyin();
        $spu_header = $pinyin->abbr($name);
        $spu_body = date('ymdHis').mt_rand(10, 99);
        return $spu_header.$spu_body;
    }

    /**
     * 验证SPU格式是否正确
     * @param $spu_sn string SPU序号
     * @param $name string 生成SPU的名称
     * @return bool
     */
    public function checkSpuHandle($spu_sn, $name)
    {
        $pinyin = new Pinyin();
        $spu_header = $pinyin->abbr($name);
        $preg = "/^($spu_header)([\d]{12})[\d]{2}$/";
        preg_match($preg, $spu_sn, $match);
        if(empty($match)){
            return false;
        }
        $tmp_date = substr(date('Y'), 0, 2).$match[2];
        $time = strtotime($tmp_date);
        if(!$time){
            return false;
        }
        return true;
    }

    /**
     * 生成sku算法
     * @param $spu_sn
     * @return string
     */
    public function setSkuHandle($spu_sn)
    {
        $sku_body = strtolower(Str::random(6)).mt_rand(0,9);
        return $spu_sn.$sku_body;
    }
}
